﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Security.Cryptography;

namespace HTComics.Data
{
    public class Order
    {
        public static string CreateOrder(string userId, out string orderCode)
        {
            string orderId = "-1";
            orderCode = GenerateOrderCode();
            DataTable dtOrder = Common.GetDataTable("SP_CREATE_ORDER @UserId=" + userId + ",@OrderCode='" + orderCode + "'");

            if (dtOrder.Rows.Count > 0)
                orderId = dtOrder.Rows[0][0].ToString();

            return orderId;
        }

        public static string CreateOrderDetails(string orderId, string comicId, string issue, string conditionId, int quantity, double price, double discount)
        {
            string orderDetId = "-1";
            DataTable dtOrderDet = Common.GetDataTable("SP_CREATE_ORDER_DETAILS @OrderId=" + orderId + ",@ComicId=" + comicId + ",@IssueNumber='" + issue + "', @ConditionId=" + conditionId + ", @Quantity=" + quantity + ", @Price=" + price + ", @Discount=" + discount);

            if (dtOrderDet.Rows.Count > 0)
                orderDetId = dtOrderDet.Rows[0][0].ToString();

            return orderDetId;
        }

        private static string GenerateOrderCode()
        {
            int maxSize = 12;
            char[] chars = new char[62];
            string a;
            a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            chars = a.ToCharArray();
            int size = maxSize;
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            size = maxSize;
            data = new byte[size];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(size);
            foreach (byte b in data)
            { result.Append(chars[b % (chars.Length - 1)]); }
            return result.ToString();
        }
    }
}
